/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dumbchat;

import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.MessageEvent;


/**
 *
 * @author tangd
 */
public class RandChanModule extends ListenerAdapter {
    private LinkedHashSet<String> enabledChannels;
    private String defaultBoard;
    private LinkedHashSet<String> boards = new LinkedHashSet<String>();
    private LinkedList<Long> timeLog = new LinkedList<Long>();
    private static final int MAX_LOG = 3;
    private static final long MAX_TIME = 30*1000;
    public RandChanModule(LinkedHashSet<String> enabledChannels, String defaultBoard) {
        String[] b = {"a","b","c","d","e","f","g","gif","h","hr","k","m","o","p","r","s","t","u","v","vg","w","wg","i","ic","r9k","cm","hm","y","3","adv","an","cgl","ck","co","diy","fa","fit","hc","int","jp","lit","mlp","mu","n","po","pol","sci","soc","sp","tg","toy","trv","tv","vp","wsg","x"};
        boards.addAll(Arrays.asList(b));
        this.enabledChannels = enabledChannels;
        this.defaultBoard = defaultBoard;
    }
    public void onMessage(MessageEvent event) {
        try {
        if(enabledChannels.contains(event.getChannel().getName())) {
            if(event.getMessage().trim().matches("!randchan(\\s+\\p{Alnum}+)?")) {
                Date d = new Date();
                long currentTime = d.getTime();
                if(timeLog.size() > MAX_LOG) {   
                    while(timeLog.size()>0 && currentTime - timeLog.getLast() > MAX_TIME) {
                        timeLog.pollLast();
                    }
                    if(timeLog.size()>MAX_LOG) {
                        event.getChannel().getBot().kick(event.getChannel(), event.getUser(), "DIAF");
                        return;
                    }   
                }
                //Russian roulette up in here
                if(((int)(Math.random()*6))==0) {
                    event.getChannel().getBot().kick(event.getChannel(), event.getUser(), "No soup for you");
                    return;
                }
                String[] splitString = event.getMessage().split("\\s+");
                if(splitString.length>1) {
                    if(boards.contains(splitString[1])) {
                        timeLog.addFirst(d.getTime());
                        event.respond(get4ChanImage(splitString[1]));
                    }
                    else {
                        event.getChannel().getBot().kick(event.getChannel(), event.getUser(), "Die");
                    }
                    //get4ChanImage(splitString[1]);
                }
                else {
                    timeLog.addFirst(d.getTime());
                    event.respond(get4ChanImage(defaultBoard));
                    //get4ChanImage(defaultBoard);
                }
            }
            
        }
        }
        catch(Exception ex) {
            ex.printStackTrace();
            System.out.println(ex.getMessage());
        }
    }
    public String get4ChanImage(String board) {
//        System.err.println("In the method");
        ArrayList<String> urls = new ArrayList<String>();
        try {
            Pattern p = Pattern.compile("http://images\\.4chan\\.org/[^ /]+/src/[^ <>\\.]+.((jpg)|(png)|(gif))");
            URL feedURL = new URL("http://boards.4chan.org/"+board+"/index.rss");
            SyndFeedInput input = new SyndFeedInput();
            URLConnection con = feedURL.openConnection();
            System.setProperty("http.agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)");
            con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)");
            con.connect();
            XmlReader xml = new XmlReader(con);
            SyndFeed feed = input.build(xml);
            List<SyndEntry> entries = feed.getEntries();
            for(SyndEntry e : entries) {
                SyndContent desc = e.getDescription();
                //System.out.println("loop "+desc.getValue());
                Matcher m = p.matcher(desc.getValue());
                if(m.find()) {
//                    System.err.println("Match found ^");
                    urls.add(m.group(0));
                }
            }
            return urls.get((int)(urls.size()*Math.random()));
        }
        catch(Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return "http://i.imgur.com/JaKGGo7.jpg";
        }
    }
}
